package main

import (
	"fmt"
	"github.com/brian-armstrong/gpio"
	"net/http"
	"os"
	"path"
	"time"
)

var qianStop int64
var houStop int64
var zuoStop int64
var youStop int64

func main() {

	qian := gpio.NewOutput(20, false)
	go func() {
		for true {
			if time.Now().UnixMilli()-qianStop < 500 {
				e := qian.High()
				if e != nil {
					println(e.Error())
				}
			} else {
				e := qian.Low()
				if e != nil {
					println(e.Error())
				}
			}
			time.Sleep(10 * time.Millisecond)
		}
	}()
	hou := gpio.NewOutput(21, false)
	go func() {
		for true {
			if time.Now().UnixMilli()-houStop < 500 {
				e := hou.High()
				if e != nil {
					println(e.Error())
				}
			} else {
				e := hou.Low()
				if e != nil {
					println(e.Error())
				}
			}
			time.Sleep(10 * time.Millisecond)
		}
	}()
	zuo := gpio.NewOutput(22, false) //zuoStop
	go func() {
		for true {
			if time.Now().UnixMilli()-zuoStop < 100 {
				e := zuo.High()
				if e != nil {
					println(e.Error())
				}
			} else {
				e := zuo.Low()
				if e != nil {
					println(e.Error())
				}
			}
			time.Sleep(10 * time.Millisecond)
		}
	}()
	you := gpio.NewOutput(23, false)
	go func() {
		for true {
			if time.Now().UnixMilli()-youStop < 100 {
				e := you.High()
				if e != nil {
					println(e.Error())
				}
			} else {
				e := you.Low()
				if e != nil {
					println(e.Error())
				}
			}
			time.Sleep(10 * time.Millisecond)
		}
	}()

	//文件服务
	serveFile("/", "./")

	http.Handle("/api", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		r.ParseForm()
		v := r.FormValue("v")
		switch v {
		case "0":
			if qianStop < time.Now().UnixMilli()-300 {
				qianStop = time.Now().UnixMilli()
			}
		case "1":
			if houStop < time.Now().UnixMilli()-300 {
				houStop = time.Now().UnixMilli()
			}
		case "2":
			if zuoStop < time.Now().UnixMilli()-80 {
				zuoStop = time.Now().UnixMilli()
			}
		case "3":
			if youStop < time.Now().UnixMilli()-80 {
				youStop = time.Now().UnixMilli()
			}
		}

		//w.Header.Set("Access-Control-Allow-Origin", "*")
		w.Header().Set("Access-Control-Allow-Origin", "*")
		w.Write([]byte(v))
	}))

	http.ListenAndServe("0.0.0.0:8080", nil)
}

func serveFile(prefix, root string) {
	http.HandleFunc(prefix, func(writer http.ResponseWriter, request *http.Request) {
		//检验是否是文件
		url := request.RequestURI
		filePath := fmt.Sprintf("%s%s", root, url)
		fileInfo, e := os.Stat(fmt.Sprintf("%s%s", root, url))
		if os.IsNotExist(e) || fileInfo.IsDir() {
			//不是文件,读取首页
			filePath = fmt.Sprintf("%s/index.html", root)
		} else {
			if !os.IsNotExist(e) {
				writer.Header().Set("Cache-Control", "public, max-age=31536000")
				if path.Ext(fileInfo.Name()) == ".css" {
					//content-type: text/css
					writer.Header().Set("Content-Type", "text/css")
				}
			}
		}
		content, e := os.ReadFile(filePath)
		if e != nil {
			println(e.Error())
		}
		_, e = writer.Write(content)
		if e != nil {
			println(e.Error())
		}
	})
}
